from Utils.kdeemul import *
from qtxml import *
import signal

class ServiceFinder(KProcIO):
	def __init__(self,type='_http._tcp'):
		KProcIO.__init__(self)
		self.type = type
		self.setExecutable("nice")
		self.setArguments(["howlxml_browse",type])
		QObject.connect(self,SIGNAL("processExited(KProcess *)"),self.endProcess)
		QObject.connect(self,SIGNAL("readReady(KProcIO *)"),self.gotOutput)

	def startFinding(self):
		print "starting finder for",self.type
		self.start()
		print "started"

	def gotOutput(self,io):
		(count,line,more) = self.readln(False)
		line = str(line)
		#print line
		dom = QDomDocument()
		if dom.setContent(line):
			root = dom.documentElement().toElement()
			self.processItem(root)
		self.ackRead()
	
	def processItem(self,element):
		tag = element.tagName()
		if tag=='resolve':
			#print "got resolve"
			name = element.attribute('name','bad_name')
			type = element.attribute('type','bad_type');
			address = element.attribute('address','127.0.0.1')
			port = int(str(element.attribute('port','8888')))
			#print name,type,address,port
			self.emit(PYSIGNAL('addService'),(name,type,address,port))
		elif tag=='removeservice':
			#print "got remove"
			name = element.attribute('name')
			type = element.attribute('type')
			self.emit(PYSIGNAL('removeService'),(name,type))
	
	def gotError(self,process,buffer,bufferlen):
		print "ServiceFinder:error:",self.type,buffer

	def endProcess(self,process):
		print "ServiceAdvertiser:endProcess",self.type

	def killTasks(self):
		print "killing finder for",self.type
		self.kill(signal.SIGINT)
		print "killed"
